# 公共的过滤器
from flask import session, current_app, g

import functools


def do_index_class(index):
    if index == 1:
        return "first"
    elif index == 2:
        return "second"
    elif index == 3:
        return "third"
    else:
        return ""


# def query_user_data():
#     user_id = session.get("user_id", None)
#     user = None  # 防止user查询失败报错,提前初始化
#     if user_id:
#         try:
#             user = User.query.get(user_id)
#         except Exception as e:
#             current_app.logger.error(e)
#         return user
#     return None

def user_login_data(f):
    """
    自定义user查询装饰器
    :param f:
    :return:
    """
    # 使用functools.wraps去装饰内层函数,可以保持当前装饰器去装饰的函数的__name__的值不变.
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        # 进行数据查询
        user_id = session.get("user_id", None)
        user = None
        if user_id:
            try:
                from info.models import User
                user = User.query.get(user_id)
            except Exception as e:
                current_app.logger.error(e)
        # 将查询出来的结果赋值给g变量
        g.user = user

        return f(*args, **kwargs)

    return wrapper
